<template>
	<div class="cart">
		<receiving-address :addressData="addressData" ></receiving-address>
		<el-table ref="multipleTable" :data="dataArray" stripe:true tooltip-effect="dark"
			style="width: 100%;margin-top: 20px;" :reserve-selection="true" :row-key="(row) => { return row.id }"
			@selection-change="handleSelectionChange" :row-class-name="rowClassName">
			<div slot="empty" style="text-align: left;">
				<el-empty description="哎呀，你是不是忘记加购啦！" />
			</div>
			<el-table-column type="selection" width="55"> </el-table-column>
			<el-table-column label="商品">
				<template slot-scope="scope">
					<div class="goods">
						<img :src="$store.state.imgShowRoad2 + '/file/' + scope.row.shopPicture" alt="" />
						<div class="info">
							<h4 class="title">{{ scope.row.farmName }}</h4>
							<span class="spec-cart">规格：{{ scope.row.specificationBean.znSpecTitle }}</span>
						</div>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="单价" width="120">
				<template slot-scope="scope">
					<p class="price">￥{{ scope.row.specificationBean.znSpecPrice }}</p>
				</template>
			</el-table-column>
			<el-table-column label="数量" width="280">
				<template slot-scope="scope">
					<el-input-number 
					v-model="scope.row.count" 
					@change="handleChange($event,scope.row)" :min="1"
					:max="scope.row.specificationBean.inventory" style="width:150px;">
					</el-input-number>
				</template>
			</el-table-column>
			<el-table-column label="操作" show-overflow-tooltip width="100">
				<template slot-scope="scope">
					<el-button type="info" class="delete-bar" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div style="margin-top: 20px" class="cancle">
			<el-button @click="toggleSelection()">取消选择</el-button>
		</div>
		<div class="submit">
			<div class="total-price">
				<span>总价:￥{{ totalprice }}</span>
			</div>
			<el-button type="danger" @click="payment()" class="place-order">提交订单</el-button>
		</div>
	</div>
</template>

<script>
	import ReceivingAddress from "@/components/foreground/ReceivingAddress.vue";
	import cartApi from "@/api/cart.js"
	import orderApi from "@/api/order.js"
	import addressApi from "@/api/address.js"
	export default {
		components: {
			ReceivingAddress
		},
		data() {
			return {
				dataArray: [],
				totalprice: "",
				addressData: []
			};
		},
		watch: {
			multipleSelection(val1, val2) {
				console.log('11111val1', val1)
				console.log('1111val2', val2)
			},
			dataArray(val) {
				console.log('222222val1', val)
			}
		},
		computed: {},
		methods: {
			async CheckCart() { //查询购物车列表
				const res = await cartApi.CheckCart('/znShoppingcart/showCart');
				if (res.code == 200) {
					this.dataArray = res.data;
				}
			},

			//获取当前的行数
			rowClassName({
				row,
				rowIndex
			}) {
				//把每一行的索引放进row
				row.index = rowIndex;
			},
			async payment() { //提交订单
				let data = {
					addressId: this.addressData.addressId,
					totalPrice: this.totalprice,
					shoppingcartList: this.multipleSelection,
				}
				if (this.multipleSelection && this.multipleSelection.length > 0) {
					const res = await orderApi.SubmitAnOrder(`/znShoppingcart/commitOrder`, data)
						.then((res) => {
							this.$message({
								message: res.msg,
								type: 'success'
							});
							this.CheckCart();
							this.totalprice = ''
						})
						.catch((err) => {
							this.$message.error(res.msg);
						});
				} else {
					this.$message.error('请选择商品')
				}
			},
			handleDelete(row) { //删除点击事件
				this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.deleteClick(row),
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			async deleteClick(row) { //删除购物车商品
				const res = await cartApi.DeleteCartFarm("/znShoppingcart/DeleteCartFarm/" + row.shoppingId);
				this.CheckCart();
			},
			async defaultAddress() { //默认地址
				const res = await addressApi.defaultAddress('/znDeliveryAddress/defaultAddress');
				if (res.code == 200) {
					this.addressData = res.data;
				}
			},
			toggleSelection(rows) {
				if (rows) {
					rows.forEach((row) => {
						this.$refs.multipleTable.toggleRowSelection(row);
					});
				} else {
					this.$refs.multipleTable.clearSelection();
					this.totalprice = ''
				}
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
				console.log(val)
				localStorage.setItem('multipleSelection', JSON.stringify(this.multipleSelection))
				let sum = 0
				val.forEach(e => {
					sum = sum + (Number(e.specificationBean.znSpecPrice) * e.count)
					this.totalprice = sum.toFixed(2);
					console.log('this.totalprice', this.totalprice)
				})
			},
			calPrice() {
				let sum = 0
				this.multipleSelection = JSON.parse(localStorage.getItem('multipleSelection'))
				if (this.multipleSelection && this.multipleSelection.length > 0) {
					this.dataArray.forEach(e => {
						this.multipleSelection.forEach(e1 => {
							if (e.shoppingId === e1.shoppingId) {
								console.log('e1.shoppingId', e.count, e1.shoppingId)
								sum = sum + (Number(e1.specificationBean.znSpecPrice) * e.count)
								this.totalprice = sum.toFixed(2);
								console.log('---this.totalprice', this.totalprice)
							}
						})
					})
				} else {
					this.totalprice = 0
				}
			},
			// 更新商品数量  /cart/update/{id}/{count}
			async handleChange(val, row) {
				if (this.multipleSelection && this.multipleSelection.length > 0) {
					this.multipleSelection.forEach(e => {
						if (e.shoppingId === row.shoppingId) {
							e.count = val
						}
					})
					localStorage.setItem('multipleSelection', JSON.stringify(this.multipleSelection))
				}
				const res = await cartApi.UpdateCount("/znShoppingcart/update/" + row.shoppingId + "/" + val)
					.then(res => {
						this.multipleSelection = JSON.parse(localStorage.getItem('multipleSelection'))
						this.calPrice()
					}).catch(err => {
						console.log(err)
					})
			},
		},
		created() {
			this.defaultAddress();
			this.CheckCart();
		},
	};
</script>

<style lang="scss" scoped>
	.cart {
		width: 1100px;
		margin: 10px auto;
		background: #fff;
		padding: 10px 20px;

		.goods {
			width: 500px;

			img {
				float: left;
				width: 150px;
				height: 100px;
				margin-right: 10px;
				border-radius: 6px;
			}

			.info {
				// float: left;
				display: flex;
				flex-direction: column;
				justify-content: flex-start;
				align-items: flex-start;

				.title {
					margin: 0;
				}
				.spec-cart{
					margin: 0;
					font-size: 12px;
				}
				.content {
					// width: 200px;
					/*超出的部分隐藏*/
					overflow: hidden;
					/*文字用省略号替代超出的部分*/
					text-overflow: ellipsis;
					/*弹性伸缩盒子模型显示*/
					display: -webkit-box;
					/*限制在一个块元素显示文本的行数*/
					-webkit-line-clamp: 3;
					/*设置或检索伸缩盒对象的子元素排列方式*/
					-webkit-box-orient: vertical;
				}
			}
		}

		.price,
		.subtotal {
			color: red;
		}

		.count {
			.itxt {
				width: 40px;
				height: 30px;
				margin: 0 10px;
			}

			button {
				display: inline-block;
				width: 20px;
				height: 20px;
				padding: 0;
				text-align: center;
				line-height: 20px;
				border: 1px solid darkgray;
				font-size: 20px;
			}
		}

		.cancle {
			float: left;
		}

		.submit {
			margin-top: 20px;
			float: right;
			width: 300px;
			height: 40px;

			.total-price {
				font-size: 20px;
				float: left;
				color: red;
				// margin-right: 50px;
				line-height: 40px;
			}

			.place-order {
				float: right;
			}
		}
	}

	.delete-bar {
		width: 60px;
		height: 30px;
		padding: 0;

		span {
			margin: 0;
		}
	}
</style>